package org.gruposp2p.proyectokarma.controller

import javax.persistence.Column;
import grails.converters.JSON
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.Authentication;
import org.gruposp2p.proyectokarma.domain.Address;
import org.gruposp2p.proyectokarma.domain.PeerAddress;

class AddressController {
	
	def springSecurityService

	def save = {
		def userDetails = springSecurityService.principal
		def peer = Peer.get(userDetails.id)
		def address = new Address(value:request.JSON.value, 
			postalCode:request.JSON.postalCode, locality:request.JSON.locality, 
			province:request.JSON.province, country:request.JSON.country);
		address.save()
		def result = [id: address.id, value:address.value, 
			postalCode:address.postalCode, locality:address.locality, 
			province:address.province, country:address.country]
		def peerAddress = new PeerAddress(peer:peer, address:address)
		peerAddress.save()
		response.status = 201
		response.setHeader('Location', grailsApplication.config.grails.serverURL + '/addresses/' + address.id)
		withFormat{
			html{
			  return result
			}
			json {
				render result as JSON
			}
		}
	}
	
	
	def show = {
		def addressList = []
		def addressMap = new HashMap()
		if (params.ids?.size() > 0) {
			Address.getAll(params.ids).collect {address ->
				if (address) addressList << address;
			}
			if (addressList.size() == 0) {
				response.status = 404 //Not Found
				render message(code: 'proyectokarma.address.addressNotFound', args:[params.ids])
				return
			}
		} else {
			addressList =  Address.list(params)
			addressMap.offset = params.offset
		}
		addressMap.numberOfAddressesInSystem = Address.count()
		addressMap.numberOfAddressesInRequest = addressList.size()
		addressMap.addresses = addressList.collect {address ->
			return [id: address.id, value: address.value, postalCode:address.postalCode, 
				locality:address.locality, province:address.province, ountry:address.country ]
		}
		withFormat{
			html{
			  return [addressMap:addressMap]
			}
			json {
				render addressMap as JSON
			}
		}
	}
	
	def update = {}
	
	def delete = {
		if (params.id) {
			def address = Address.get(params.id)
			if (address) address.delete()
			else {
				response.status = 404;
				render message(code: 'proyectokarma.address.deleteNotFound', args:[params.id])
				return
			}
			response.status = 200;
			render message(code: 'proyectokarma.address.deleteOK', args:[params.id])
			return
		} else {
			response.status = 400  //Bad Request
			render message(code: 'proyectokarma.address.deleteBadRequest')
			return;
		}
	}
    
}
